<?php
class S3BucketList {
	private $bucket;
	private $s3;
	private $opened = false;
	private $objects;
	
	private $EOL = false;
	
	public function __construct($bucket = null) {
		if (!is_null($bucket)) {
			$this->bucket($bucket);
		}
		$this->s3 = new AmazonS3();
	}
	
	public function EOL() {
		return $this->EOL;
	}
	
	public function bucket($bucket = null) {
		if (!is_null($bucket)) {
			$this->bucket = $bucket;
		}
		return $bucket;
	}

	private function __list($nextMarker = null) {
		$opts = array();
		if (!is_null($nextMarker)) {
			$opts["key-marker"] = $nextMarker;
		}
		$this->opened = true;
		$res = $this->s3->list_bucket_object_versions($this->bucket, $opts);
		if ($res->isOK()) {
			foreach ($res->body->Version as $object) {
				$metaRes = $this->s3->get_object_metadata($this->bucket, (string) $object->Key, array("versionId" => (string) $object->VersionId));
				$cryptID = null;
				if (isset($metaRes["Headers"]["x-amz-meta-crypt"])) {
					$cryptID = $metaRes["Headers"]["x-amz-meta-crypt"];
				}
				$this->objects[] = new S3Object($object, false, $cryptID);
			}
			foreach ($res->body->DeleteMarker as $object) {
				$this->objects[] = new S3Object($object, true);
			}
			if (isset($res->body->IsTruncated) && ((string) $res->body->IsTruncated == "true")) {
				$nextMarker = (string) $res->body->NextKeyMarker;
				$this->__list($nextMarker);
			}
		}
	}
	
	public function next() {
		if ($this->opened === false) {
			$this->__list();
			return current($this->objects);
		}
		$next = next($this->objects);
		if ($next === false) {
			$this->EOL = true;
		}
		//$this->current = current($this->objects);
		return $next;
	}
	
	public function count() {
		if ($this->opened === false) {
			$this->__list();
		}
		return count($this->objects);
	}
}
?>